package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Category;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.AdminCatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/catalog")
public class AdminProductController {

    @Autowired
    private AdminCatalogService adminCatalogService;

    // 获取所有类别
    @ModelAttribute("categories")
    public List<Category> getCategories() {
        return adminCatalogService.getCategoryList();
    }

    @GetMapping("/AdminEditProduct")
    public String listProducts(Model model) {
        List<Product> products = adminCatalogService.listProducts();  // 从数据库获取产品列表
        model.addAttribute("products", products);  // 将产品列表传递到页面
        return "admin/productList";
    }

    @GetMapping("/AdminAddProduct")
    public String editProduct(@RequestParam(required = false) String productId, Model model) {
        if (productId != null) {
            Product product = adminCatalogService.getProduct(productId);
            model.addAttribute("product", product);
        } else {
            model.addAttribute("product", new Product());
        }
        return "admin/editProduct";
    }

    @PostMapping("/saveProduct")
    public String saveProduct(@ModelAttribute Product product) {
        if (product.getProductId() == null || product.getProductId().trim().isEmpty()) {
            // 如果 productId 为空，则为新产品，执行新增操作
            adminCatalogService.addProduct(product);
        } else {
            // 检查该 productId 是否已经存在
            Product existingProduct = adminCatalogService.getProduct(product.getProductId());
            if (existingProduct != null) {
                // 如果产品存在，则执行更新操作
                adminCatalogService.updateProduct(product);
            } else {
                // 如果产品不存在，则执行新增操作
                adminCatalogService.addProduct(product);
            }
        }
        // 无论是新增还是更新后，重定向到产品列表页面
        return "redirect:/catalog/AdminEditProduct";
    }

    @GetMapping("/deleteProduct")
    public String deleteProduct(@RequestParam String productId) {
        adminCatalogService.deleteProduct(productId);
        return "redirect:/catalog/AdminEditProduct";
    }

    @GetMapping("/publishProduct")
    public String publishProduct(@RequestParam String productId) {
        adminCatalogService.publishProduct(productId);
        return "redirect:AdminEditProduct";
    }
}
